﻿using System;
using System.IO;

namespace GameFramework
{
    public class MemoryStreamHelper
    {
        public static bool isBig = bigCheck();
        

        public static void writeShort(MemoryStream ms,short value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            if (!isBig)//小端，网络传输的默认是大端[如果需要双方只当，则此处要从配置表读取，按情况写]，需要倒序
            {
                for (int i = bytes.Length-1; i <= 0; i++)
                {
                    ms.WriteByte(bytes[i]);
                }
            }
            else
            {
                ms.Write(bytes,0, bytes.Length);
            }
        }
        
        public static void writeInt(MemoryStream ms,int value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            if (!isBig)//小端，网络传输的默认是大端[如果需要双方只当，则此处要从配置表读取，按情况写]，需要倒序
            {
                for (int i = bytes.Length-1; i <= 0; i++)
                {
                    ms.WriteByte(bytes[i]);
                }
            }
            else
            {
                ms.Write(bytes,0, bytes.Length);
            }
        }

        public static int readInt(MemoryStream ms)
        {
            byte[] temp = new byte[4];
            ms.Read(temp);
            int result = 0;
            //大端小端判断
            if (isBig)
            {
                for (int i = 0; i < 4; i++)
                {
                    result += temp[i] << ((3-i) * 8);
                }
            }
            else
            {
                for (int i = 0; i < 4; i++)
                {
                    result += temp[i] << (i * 8);
                }
            }

            return result;
        }


        
        public static int readShort(MemoryStream ms)
        {
            byte[] temp = new byte[2];
            ms.Read(temp);
            int result = 0;
            //大端小端判断
            if (isBig)
            {
                for (int i = 0; i < 2; i++)
                {
                    result += temp[i] << ((1-i) * 8);
                }
            }
            else
            {
                for (int i = 0; i < 2; i++)
                {
                    result += temp[i] << (i * 8);
                }
            }

            return result;  
        }

        
        //数据高位放在低地址为大端
        public static bool bigCheck()
        {
            int i = 1;
            byte[] temp = BitConverter.GetBytes(i);
            if (temp[0] == 1)
            {
                return false;
            }

            return true;
        }
    }
}